import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import babel from '@rollup/plugin-babel';
import json from '@rollup/plugin-json';
import { readdirSync } from 'fs';
import { join } from 'path';

// 动态获取 src 目录下的所有 .ts 文件（排除 .d.ts 文件）
function getInputFiles() {
  const srcDir = 'src';
  const files = readdirSync(srcDir)
    .filter(file => file.endsWith('.ts') && !file.endsWith('.d.ts'))
    .map(file => file.replace('.ts', ''));
  
  return files;
}

// 生成通用插件配置
function getPlugins() {
  return [
    resolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    json(),
    typescript({
      declaration: false
    }),
    babel({
      exclude: 'node_modules/**',
      presets: [
        ['@babel/preset-env', { targets: '> 0.25%, not dead' }]
      ],
      babelHelpers: 'bundled'
    })
  ];
}

// 动态生成配置
const configs = getInputFiles().map(fileName => {
  const config = {
    input: `src/${fileName}.ts`,
    output: {
      file: `lib/${fileName}.js`,
      format: 'esm',
      sourcemap: false
    },
    plugins: getPlugins(),
    external: ['element-plus', 'umi-request', 'html2canvas', 'jspdf', 'crypto-js', 'qs', 'cookie']
  };

  // 如果是 index.ts，添加额外的 external 配置
  if (fileName === 'index') {
    const otherFiles = getInputFiles().filter(f => f !== 'index');
    config.external = [...config.external, ...otherFiles.map(f => `./${f}`)];
  }

  return config;
});

export default configs;
    